/**
 * 
 */
package com.snapp.util;

import java.util.Iterator;
import java.util.Vector;

import org.jdom.Element;
import org.jdom.JDOMException;

import com.snapp.util.object.model.ObjectModel;

/**
 * Build a hierarchy of xml given a vector of SNAppObjects
 * - A "parentProperty" name must be given to link each object to its parent
 * 
 * @author kile
 *
 */
public class Hierarchy {
	
	/*
	 * Root dom element
	 */
	private Element root = null;
	
	/*
	 * The property linked to the id of the parent
	 */
	private String parentProperty = "parent";
	
	/**
	 * Default constructor.  
	 * Kicks off recursion to build layers of the hierarchial structure
	 *
	 * @param list
	 * @param parentName
	 */
	public Hierarchy(Vector<ObjectModel> list, String parentName) {
		buildHierarchy(list, null, null);
	}
	
	/**
	 * Recursively builds layers of hierarchy
	 * 
	 * @param list
	 * @param parent
	 * @param pEl
	 */
	private void buildHierarchy(Vector<ObjectModel> list, String parent, Element pEl) {
		if (pEl == null) {
			root = new Element("root");
			pEl = root;
		}
		
		//logger.info("adding content for parent: "+parent+ " > name: " + pEl.getName());
		// parent list..
		Iterator<ObjectModel> itr = list.iterator();
		while (itr.hasNext()) {
			
			ObjectModel nxt = itr.next();
			if (nxt.getBean().getPropertyString(parentProperty).equals(parent)) {
				//logger.info("Adding child of "+parent+".  ID is "+nxt.getBean().getPropertyString("id"));
				Element nel = null;
				try {
					nel = nxt.getBean().toXML();
					pEl.addContent(nel);
				} catch (JDOMException e) {
					//logger.warn("Could not parse user function to xml.",e);
				}
				
				buildHierarchy(list, nxt.getId(), nel);
			}
		}
		
	}

	public Element getRoot() {
		return root;
	}

	public void setRoot(Element root) {
		this.root = root;
	}

	public String getParentProperty() {
		return parentProperty;
	}

	public void setParentProperty(String parentProperty) {
		this.parentProperty = parentProperty;
	}
}
